package com.main.tripplanner.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.stereotype.Service;

import com.main.tripplanner.persistent.Attraction;
import com.main.tripplanner.persistent.Attraction.AttractionType;
import com.main.tripplanner.persistent.City;
import com.main.tripplanner.persistent.Dosage;
import com.main.tripplanner.persistent.Route;
import com.main.tripplanner.service.AbstractService;
import com.main.tripplanner.service.RouteService;

@Service
public class RouteServiceImpl extends AbstractService implements RouteService{

	public void updateRoute(Route route, List<Attraction> attractions, City city) {
		Set<City> cities = route.getCities();
		cities.add(city);
		route.setCities(cities);
		Set<Attraction> currentAttractions = route.getAttractions();
		if(!attractions.isEmpty()){
			currentAttractions.addAll(attractions);
			route.setAttractions(currentAttractions);
		}
		float totalAttractionsTime = 0;
		for (Attraction attraction : attractions) {
			totalAttractionsTime += attraction.getTime();
		}
		route.setCurrentTime(route.getCurrentTime() + totalAttractionsTime);
		
		route.setDosage(getUpdatedDosage(route, attractions));
	}

	private Dosage getUpdatedDosage(Route route, List<Attraction> attractions) {
		Dosage dosage = route.getDosage();
		Map<AttractionType, Float> timeForEachAttractionType = new HashMap<Attraction.AttractionType, Float>();
		for (Attraction attraction : attractions) {
			if(timeForEachAttractionType.containsKey(attraction.getAttractionType())){
				float typeTime = timeForEachAttractionType.get(attraction.getAttractionType());
				timeForEachAttractionType.put(attraction.getAttractionType(), typeTime + attraction.getTime());
			}
			else{
				timeForEachAttractionType.put(attraction.getAttractionType(), attraction.getTime());
			}
		}
		
		for (AttractionType attractionType : timeForEachAttractionType.keySet()) {
			float percentage = (timeForEachAttractionType.get(attractionType) / route.getTotalTravelTime())*100;
			if(attractionType == AttractionType.FAMILY){
				dosage.setFamilyPercentage(route.getDosage().getFamilyPercentage() + percentage);
			}
			else if(attractionType == AttractionType.NIGHT_LIFE){
				dosage.setNightLifePercentage(route.getDosage().getNightLifePercentage() + percentage);
			}
			else if(attractionType == AttractionType.TREKKING){
				dosage.setTrekkingPercentage(route.getDosage().getTrekkingPercentage() + percentage);
			}
			else if(attractionType == AttractionType.EXTREME){
				dosage.setExtremePercentage(route.getDosage().getExtremePercentage() + percentage);
			}
			else{
				dosage.setCulturePercentage(route.getDosage().getCulturePercentage() + percentage);
			}
		}
		return dosage;
	}

}
